package com.taru.wxhsh.filter;


import com.taru.wxhsh.constant.CommonConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.logging.LogRecord;


public class AuthFilter  implements Filter {
    Logger logger  = LoggerFactory.getLogger(AuthFilter.class);
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request  =(HttpServletRequest)servletRequest;
        HttpServletResponse response =(HttpServletResponse)servletResponse;

        //剔除登录页面
        if(request.getRequestURI().equals(request.getContextPath()+"/view/login")){
            logger.info("{}是登录页面,跳过拦截",request.getRequestURI());
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }


        boolean isPass =false;
        Cookie[]  cookies= request.getCookies();
        if(cookies!=null  && cookies.length>0){
                for(Cookie c:cookies){
                    if(CommonConstants.TOKEN_KEY.equals(c.getName())){
                        if(CommonConstants.SIMPLE_TOKEN.equals(c.getValue())){
                            isPass =true;
                            break;
                        }
                    }
                }
        }
        if(isPass){
            logger.info("{}携带认证,跳过拦截",request.getRequestURI());
            filterChain.doFilter(servletRequest,servletResponse);
        }else
        {
            logger.info("{}没有认证凭证,进入登录页面",request.getRequestURI());
            response.sendRedirect(request.getContextPath()+"/");
        }



    }

    @Override
    public void destroy() {

    }
}
